
layui.use(['form', 'layer', 'table', 'formSelects'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;
    var formSelects = layui.formSelects;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var handle_url = $('.handle_url').val()
    var select_url = $('.select_url').val()


    if($('#couponType').length > 0){
        formSelects.render('couponId');
    }

    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        cols : [[
            {field: 'id', title: '序号', align:'center'},
            {field: 'region', title: '配送区域',width:400, align:'center'},
            {field: 'first_weight', title: '首重（Kg）', align:'center'},
            {field: 'first_weight_price', title: '首重运费（元）', align:'center',templet:function(d){
                return formatMoney(d.first_weight_price/100,1)
            }},
            {field: 'continuous_weight_price', title: '续重运费（Kg/元）', align:'center',templet:function(d){
                return formatMoney(d.continuous_weight_price/100,1)
            }},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';

                html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';


                return html;
            }}
        ]]
    });
    var defaultval = $('#freight_type option:selected').val()
    if(defaultval == 1){
        $('#mane').hide();
        $('#tongyi').show();
    }else {
        $('#tongyi').hide();
        $('#mane').show();
    }
    // 搜索
    $(".search_btn").on("click", function(){
        if($('.name').val() != ''){
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: $('.searchBox').find('input[name=name]').val()  // 搜索的关键字
                }
            });
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function(){
        table.reload("tableList", {
            where: {
                name: ''
            }
        });
    });

    form.on('select(freight_type)', function(data){
        if(data.value == 1){
            $('#mane').hide();
            $('#tongyi').show();

        }else {
            $('#tongyi').hide();
            $('#mane').show();

        }

    })

    form.on('switch(switch_default)', function(data){
        if(!this.checked){
            $('#switch_diy').prop('checked',true)
            var mode = 2;
        }else {
            $("#switch_diy").removeAttr('checked');
            var mode = 1;
        }
        form.render();
        $.ajax({
            url: '/admin/Freight/setFreightSwitch',
            data: {"mode": mode},
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.code == 1) {
                    layer.msg('修改成功');
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    });

    form.on('switch(switch_diy)', function(data){
        if(!this.checked){
            $('#switch_default').prop('checked',true)
            var mode = 1;
        }else {
            $("#switch_default").removeAttr('checked');
            var mode = 2;
        }
        form.render();
        $.ajax({
            url: '/admin/Freight/setFreightSwitch',
            data: {"mode": mode},
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.code == 1) {
                    layer.msg('修改成功');
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });

    });

    // Status 操作
    form.on('switch(status)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});

        var status = 2;
        if(data.elem.checked){
            status = 1;
        }

        $.ajax({
            url: handle_url,
            data: {'id' : data.elem.value,'status' : status},
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if (res.code == 1) {
                    parent.layui.table.reload('tableList', {});
                } else {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });
    $('.edit_area').on('click', function(){
        var id = $('#editid').val();
        addHtml(id);
    });
	form.on('checkbox(add_all)', function(data) {
		var a = data.elem.checked;
		if(a == true) {
			$(".add").prop("checked", true);
			form.render('checkbox');
		} else {
			$(".add").prop("checked", false);
			form.render('checkbox');
		}
	
	});
	form.on('checkbox(add_one)', function(data) {
		var item = $(".add");
		for(var i = 0; i < item.length; i++) {
			if(item[i].checked == false) {
				$("#add_all").prop("checked", false);
				form.render('checkbox');
			}
		}
	});

    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // 删除
    /*$('.del-btn').on('click', function(){
        layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
            $.ajax({
                url: delete_url,
                data: {"id": data.id},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        layer.msg('已删除', {icon: 1, time: 1000});
                        tableIns.reload();
                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
        });
    });*/

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: 1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.1
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '590px'
            , top: 0
            , content: content
        });
    }
	// 选择配送区域
    function addHtml(data){
        var content = select_url;
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: 1
            , title: false
            , closeBtn: false
            , shade: 0.1
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: ['800px','500px']
            , top: 0
            , content: content
            ,success:function (layero,index) {
                $.ajax({
                    url: '/admin/Freight/getselectregion/id/' + data ,
                    type: "get",
                    dataType: "json",
                    success: function(res){
                        var selectarr = res.split(',');
                        var checkbox = $(parent.window.frames[1].document).find("input:checkbox[name='region']")
                        checkbox.each(function(){
                            for(var i=0;i<selectarr.length;i++){
                                //判断当前值是否在数组中
                                if($(this).val() == selectarr[i]){
                                    $(this).attr('disabled',true);//选中
                                }
                            }

                        });
                        var str = $(parent.window.frames[0].document).find('#selectAdd').text();
                        var arr = str.split(',')
                        checkbox.each(function(){
                            for(var i=0;i<arr.length;i++){
                                //判断当前值是否在数组中
                                if($(this).val() == arr[i]){
                                    $(this).attr('checked',true);//选中
                                }
                            }
                        });
                        if(layero.find('iframe')[0].contentWindow.layui.form){
                            layero.find('iframe')[0].contentWindow.layui.form.render();
                        }
                    },
                    error:function(data){
                        layer.msg("服务器无响应");
                    }
                });
            }
        });
    }



    // 自定义验证规则
    form.verify({

        regions: function(value){
            if(value == ''){
                return '请编辑并选择区域';
            }
        },
        first_weight: function(value){
            if(value == ''){
                return '首重必填';
            }
            if(!/(^[1-9]\d*$)/.test(value)){
                return '首重必须是正整数';
            }
        },
        first_weight_price: function(value){
            if(value == ''){
                return '首重运费必填';
            }
            if(value==0){
                return '首重运费金额有误';
            }
            if(!/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/.test(value)){
                return '首重运费金额有误';
            }

        },
        continuous_weight_price: function(value){
            if(value == ''){
                return '续重运费必填';
            }
            if(value==0){
                return '续重运费金额有误';
            }
            if(!/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/.test(value)){
                return '续重运费金额有误';
            }

        },

        unified_price:function(value){
            if($('#freight_type option:selected').val() == 1){
                if(value == ''){
                    return '统一运费必填';
                }
                if(value==0){
                    return '统一运费金额有误';
                }
                if(!/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/.test(value)){
                    return '统一运费金额有误';
                }
            }
        },
        full_amount:function(value){
            if($('#freight_type option:selected').val() == 2){
                if(value == ''){
                    return '订单金额必填';
                }
                if(value==0){
                    return '订单金额有误';
                }
                if(!/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/.test(value)){
                    return '订单金额有误';
                }
            }
        },
        s_price:function(value){
            if($('#freight_type option:selected').val() == 2){
                if(value == ''){
                    return '运费必填';
                }
                if(value==0){
                    return '运费金额有误';
                }
                if(!/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/.test(value)){
                    return '运费金额有误';
                }
            }
        },
    });

    
    form.on("submit(select_save)",function (data) {
        var arr = new Array();
        $("input:checkbox[name='region']:checked").each(function(i){
            arr[i] = $(this).val();
        });
        data.field.region = arr.join(",");//将数组合并成字符串
        if(data.field.region.trim() == ''){
            layer.msg('至少选择一个');
            return false;
        }
        var index = parent.layer.getFrameIndex(window.name);
        $(parent.window.frames[0].document).find('#selectAdd').text(data.field.region)
        $(parent.window.frames[0].document).find('#selectregions').val(data.field.region)
        layer.close(index);
        layer.msg('您选择了：'+data.field.region);
    })

    //全选
    // form.on('checkbox(add_all)', function (data) {
    //     var a = data.elem.checked;
    //     if (a == true) {
    //         $(".add").prop("checked", true);
    //         form.render('checkbox');
    //     } else {
    //         $(".add").prop("checked", false);
    //         form.render('checkbox');
    //     }
    //
    // });

    // 表单提交
    form.on("submit(laySave)", function(data){
        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    layer.closeAll("iframe");
                    parent.layui.table.reload('tableList', {});
                }else {
                    layer.msg(res.msg);
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    })

    form.on("submit(freightDefaultSave)", function(data){
        console.log(data.field)
        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        console.log(data)

        $.ajax({
            url: '/admin/Freight/setDefauleFreight',
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    layer.closeAll("iframe");
                    parent.layui.table.reload('tableList', {});
                }else {
                    layer.msg(res.msg);
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    })

});